package cn.cnhis.online.mymodule.Utils;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Build;
import androidx.core.content.FileProvider;

import java.io.File;

public class PackageUtil {
	
	/**
	 * 获取当前应用版本序号
	 * 
	 * @param context
	 * @return 当前应用版本序号
	 */
	public static int getVersionCode(Context context) {
		try {
			PackageManager packageManager = context.getPackageManager();
			PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionCode;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return -1;
		}
	}

	/**
	 * 获取当前应用版本名
	 * 
	 * @param context
	 * @return 当前应用版本名
	 */
	public static String getVersionName(Context context) {
		try {
			PackageManager packageManager = context.getPackageManager();
			PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);
			return packageInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "";
		}
	}
	
	public static ComponentName getCurComponentName(Context context){
		ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
		return am.getRunningTasks(1).get(0).topActivity;
	}

	/**
	 * 调用系统安装应用
	 */
	public static boolean install(Context context, File file) {
		String TAG = "tag";
		if (file == null || !file.exists() || !file.isFile()) {
			return false;
		}
		Intent intent = new Intent(Intent.ACTION_VIEW);
		Uri uri;
		// 判断版本大于等于7.0
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			uri = FileProvider.getUriForFile(context, "com.mbmed.doctor.fileprovider", file);
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		} else {
			uri = Uri.fromFile(file);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		}
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		context.startActivity(intent);
		return true;
	}
}
